import React, { useState } from "react";

interface ListItemProps {
	id: number;
	text: string;
	index: number;
	handleDrop: (draggedIndex: number, targetIndex: number) => void;
}

const ListItem: React.FC<ListItemProps> = ({ id, text, index, handleDrop }) => {
	const handleDragStart = (e: React.DragEvent<HTMLDivElement>) => {
		console.log(e.target);
		console.log(e.dataTransfer);
		e.dataTransfer.setData("text/plain", index.toString());
	};

	const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
		e.preventDefault();
	};

	const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
		e.preventDefault();
	};

	const handleDropInternal = (e: React.DragEvent<HTMLDivElement>) => {
		console.log(e.target);
		console.log(e.dataTransfer);
		console.log(e.dataTransfer.getData("text/plain"));
		const draggedIndex = +e.dataTransfer.getData("text/plain");
		if (draggedIndex !== index) {
			handleDrop(draggedIndex, index);
		}
	};

	return (
		<div
			draggable
			onDragStart={handleDragStart}
			onDragOver={handleDragOver}
			onDragEnter={handleDragEnter}
			onDrop={handleDropInternal}
			style={{ border: "1px solid #ccc", padding: "8px", marginBottom: "4px" }}>
			{text}
		</div>
	);
};

const App: React.FC = () => {
	const initialItems = [
		{ id: 1, text: "Item 1" },
		{ id: 2, text: "Item 2" },
		{ id: 3, text: "Item 3" }
	];

	const [items, setItems] = useState(initialItems);

	const handleDrop = (draggedIndex: number, targetIndex: number) => {
		const newItems = [...items];
		const draggedItem = newItems[draggedIndex];
		newItems.splice(draggedIndex, 1);
		newItems.splice(targetIndex, 0, draggedItem);
		setItems(newItems);
	};

	return (
		<div>
			<h1>Draggable List</h1>
			{items.map((item, index) => (
				<ListItem key={item.id} id={item.id} text={item.text} index={index} handleDrop={handleDrop} />
			))}
		</div>
	);
};

export default App;
